<?php

/**
 * 获取带宽
 * ifstat 需在通过ports安装
 */
$ifStatsCmd = '/usr/local/bin/ifstat -z 0.1 1';
$topCmd     = '/usr/bin/top -b';
$vmstatCmd  = '/usr/bin/vmstat -c 2'; //-c 2表示输出两次的信息然后退出，默认只输出一次，只输出一次时大部分情况下不准确

$r = array(
    'time'   => 0,  //服务器的时间
    'age'    => 0,  //已运行时长
    'if_in'  => 0,  //输入带宽
    'if_out' => 0,  //输出带宽
    'load'   => 0,  //负载
    'cpu'    => '', //CPU
);

/**
 * 获取带宽数据
 */
$execResult = null;
exec($ifStatsCmd, $execResult);

if(!empty($execResult) && !empty($execResult[2])) {
    if($tmp = explode(' ', preg_replace('/\s+/', ' ', trim($execResult[2])))) {
        $r['if_in']  = empty($tmp[0]) ? 0 : $tmp[0];
        $r['if_out'] = empty($tmp[1]) ? 0 : $tmp[1];
    }
}

/**
 * 获取运行时长及服务器时间
 */
$execResult = null;
exec($topCmd, $execResult);

if(!empty($execResult[0])) {
    preg_match('/load averages:(.*?)up(.*)/', $execResult[0], $tmp);

    if(!empty($tmp[2])) {
        $tmp2      = explode(' ', preg_replace('/\s+/', ' ', trim($tmp[2])));
        $r['age']  = $tmp2[0];
        $r['time'] = $tmp2[1];
    }
}

/**
 * 获取CPU使用率
 */
$execResult = null;
exec($vmstatCmd, $execResult);

if(!empty($execResult[3])) {
    $tmp     = preg_replace('/\s+/', ' ', trim($execResult[3]));
    $vmstats = explode(' ', $tmp);
    $idle    = array_pop($vmstats);

    $r['load'] = empty($idle) ? 0 : 100 - $idle;
}

/**
 * 获取CPU信息
 */
$execResult = null;
exec('/sbin/sysctl hw.model && /sbin/sysctl hw.ncpu', $execResult);

if(!empty($execResult)) {
    $cpu      = '';
    $cpuTotal = '';

    if(!empty($execResult[0])) {
        $cpu = trim(str_replace('hw.model:', '', $execResult[0]));
    }

    if(!empty($execResult[1])) {
        $cpuTotal = trim(str_replace('hw.ncpu:', '', $execResult[1]));
    }

    $r['cpu'] = $cpu . " [ {$cpuTotal} ]";
}

exit(json_encode($r));
